#!/bin/bash

# show the file number, line, and character count of each language in current dir

declare -A language_stats
total_files=0
total_lines=0
total_chars=0

function process_file() {
    local file="$1"
    local extension="${file##*.}"  # get suffix
    case "$extension" in
        c|h) language="C" ;;
        cpp|cxx|cc|h|hpp|hxx) language="C++" ;;
        java) language="Java" ;;
        py) language="Python" ;;
        js) language="JavaScript" ;;
        sh) language="Shell" ;;
        scala) language="Scala" ;;
        swift) language="Swift" ;;
        kt) language="Kotlin" ;;
        rs) language="Rust" ;;
        rb) language="Ruby" ;;
        pl) language="Perl" ;;
        php) language="PHP" ;;
        lua) language="Lua" ;;
        bat) language="Win_Batch" ;;
	go) language="Go" ;;
        # add other languages here
        *) return ;;
    esac

    if [[ -z "${language_stats[$language]}" ]]; then
        language_stats["$language"]="0 0 0"
    fi

    lines=$(wc -l < "$file")
    chars=$(wc -c < "$file")
    current_stats=(${language_stats["$language"]})
    new_stats=("$((current_stats[0] + 1))" "$((current_stats[1] + lines))" "$((current_stats[2] + chars))")
    language_stats["$language"]="${new_stats[0]} ${new_stats[1]} ${new_stats[2]}"

    ((total_files++))
    ((total_lines+=lines))
    ((total_chars+=chars))
}

while IFS= read -r -d $'\0' file; do
    process_file "$file"
done < <(find . -type f -name "*.*" -print0)

# sort the result and print
printf "%-10s    Files    Lines    Characters\n"
for language in "${!language_stats[@]}"; do
    stats=(${language_stats["$language"]})
    printf "%-12s  %-8s %-8s %s\n" "$language" "${stats[0]}" "${stats[1]}" "${stats[2]}"
done | sort -k4,4nr

# print total files, lines, and characters
echo "--------------------------------------------"
printf "%-12s  %-8s %-8s %s\n" "TOTAL" "$total_files" "$total_lines" "$total_chars"

exit 0
